package com.moss.system.service.impl;

import com.moss.common.domain.TreeEntity;
import com.moss.common.entity.SysGoodsCategoryEntity;
import com.moss.system.mapper.GoodsCategoryMapper;
import com.moss.system.service.GoodsCategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Resource
    GoodsCategoryMapper goodsCategoryMapper;


    @Override
    public List<SysGoodsCategoryEntity> selectList() {
        return goodsCategoryMapper.selectList();
    }



    @Override
    public List<TreeEntity> buildTree(List<SysGoodsCategoryEntity> list) {
        Set<Long> ids = list.stream()
                .map(SysGoodsCategoryEntity::getId)
                .collect(Collectors.toSet());

        List<SysGoodsCategoryEntity> collect = list.stream()
                .filter(m -> !ids.contains(m.getParentId()))
                .peek(m -> m.setChildren(getChildrenList(m, list)))
                .collect(Collectors.toList());
        return collect.stream().map(TreeEntity::new).collect(Collectors.toList());
    }

    private List<SysGoodsCategoryEntity> getChildrenList(SysGoodsCategoryEntity root, List<SysGoodsCategoryEntity> all) {
        return all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).peek(
                (m) -> m.setChildren(getChildrenList(m, all))
        ).collect(Collectors.toList());
    }
}
